package org.quadraspace.resource;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.logging.Log;
import org.quadraspace.model.Event;
import org.quadraspace.service.EventRepository;

import org.apache.commons.logging.LogFactory;

@Path("/motes/{moteID}/events")
@Produces(MediaType.APPLICATION_XML)
@Consumes(MediaType.APPLICATION_XML)
public class EventsResource {
	private EventRepository repository;
	private static Log logger = LogFactory.getLog(EventsResource.class);
	public void setRepository(EventRepository repostory) {
		this.repository = repostory;
	}
	@GET
	public List<Event> getIt(@PathParam("moteID") String moteId,
			@DefaultValue("-1") @QueryParam("starttime") long starttime,
			@DefaultValue("-1") @QueryParam("endtime") long endtime) {
		List<Event> toRet = null;
		if (starttime != -1 && endtime != -1) {
			logger.trace("finding all events for mote "+moteId+" in the time range ["+starttime+";"+endtime+"]");
			toRet = repository.getEventsForMoteWithId(moteId, starttime, endtime);
		} else {
			logger.trace("get all events for mote with id: "+ moteId);
			toRet = repository.getEventsForMoteWithId(moteId);
		}
		return toRet;
	}	
	
	@POST
	public Response postEvent(@PathParam("moteID") String moteId, Event toSave) {
		logger.trace("the event is timestamped "+toSave.getTimestamp());
		repository.addEventForMoteWithID(moteId, toSave);
		logger.trace("added it to mote with id "+moteId);
		return Response.status(201).build();
	}
}
